﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using TrafficCountingTool.Core;
using TrafficCountingTool.Models;
using TrafficCountingTool.Windows;

namespace TrafficCountingTool.ViewModel
{
    public class MainWindowViewModel : ViewModel
    {
        private AppCache _appCache;
        private string _vedioFilePath;
        private bool _canWorking;
        private bool _mediaLoaded;
        private ObservableCollection<DisplayingVehicleCounting> _vehicleCountings; 

        public AppCache AppCache
        {
            get { return _appCache; }
            set { SetProperty(ref _appCache, value); }
        }

        public string VedioFilePath
        {
            get { return _vedioFilePath; }
            set
            {
                if (_vedioFilePath != value)
                {
                    SetProperty(ref _vedioFilePath, value);
                    SendMessage("LoadNewMedia");
                }
                else
                {
                    SetProperty(ref _vedioFilePath, value);
                }

                AppCache.MediaFilePath = value;
            }
        }

        public bool CanWorking
        {
            get { return _canWorking; }
            set { SetProperty(ref _canWorking, value); }
        }

        public bool MediaLoaded
        {
            get { return _mediaLoaded; }
            set { SetProperty(ref _mediaLoaded, value); }
        }

        public ObservableCollection<DisplayingVehicleCounting> VehicleCountings
        {
            get { return _vehicleCountings; } 
            set { SetProperty(ref _vehicleCountings, value); }
        }

        #region Commands
        private ICommand _openProjectFileCommand; 
        private ICommand _saveProjectFileCommand; 
        private ICommand _saveAsProjectFileCommand; 
        private ICommand _importFileCommand; 
        private ICommand _exportFileCommand; 
        private ICommand _extCommand;
        private ICommand _openSettingWindowCommand;

        public ICommand OpenProjectFileCommand
        {
            get
            {
                return _openProjectFileCommand ?? (_openProjectFileCommand = new DelegateCommand(o =>
                {
                    if (AppCache.ProjectFileOpened && MessageBox.Show("将放弃保存当前文件，是否继续?", "警告", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    {
                       return;
                    }

                    AppCache = SavingHelper.LoadFile();
                    if (AppCache == null)
                    {
                        return;
                    }

                    if (AppCache.NoMediaModeOn == false && AppCache.MediaFilePath != null)
                    {
                        VedioFilePath = AppCache.MediaFilePath;
                        MediaLoaded = true;
                    }

                    VehicleCountings.Clear();
                    foreach (var c in AppCache.VehicleCountings)
                    {
                       VehicleCountings.Add(c.ToDisplayingVehicleCounting()); 
                    }

                    CanWorking = true;

                    RaiseAllCommandCanExecuteChanged();
                }));
            }
        }

        public ICommand SaveProjectFileCommand
        {
            get
            {
                return _saveProjectFileCommand ?? (_saveProjectFileCommand = new DelegateCommand(o =>
                {
                    AppCache.VehicleCountings = VehicleCountings.Select(v => v.ToVehicleCounting()).ToList();
                    SavingHelper.SaveFile(AppCache);
                },
                    o => AppCache.ProjectFileOpened));
            }
        }

        public ICommand SaveAsProjectFileCommand
        {
            get
            {
                return _saveAsProjectFileCommand ?? (_saveAsProjectFileCommand = new DelegateCommand(o => {}, o => false));
            }
        }

        public ICommand ImportFileCommand
        {
            get
            {
                return _importFileCommand ?? (_importFileCommand = new DelegateCommand(o =>
                {
                    var path = SavingHelper.ImportFile();

                    if (string.IsNullOrEmpty(path))
                    {
                        return;
                    }

                    VedioFilePath = path;

                    AppCache.ProjectFileOpened = true;
                    CanWorking = true;
                    MediaLoaded = true;

                    RaiseAllCommandCanExecuteChanged();
                },
                o => !AppCache.NoMediaModeOn));
            }
        }

        public ICommand ExportFileCommand
        {
            get
            {
                return _exportFileCommand ?? (_exportFileCommand = new DelegateCommand(o =>
                {
                    AppCache.VehicleCountings = VehicleCountings.Select(v => v.ToVehicleCounting()).ToList();
                    SavingHelper.ExportFile(AppCache);
                },
                    o => AppCache.ProjectFileOpened));
            }
        }

        public ICommand ExitCommand
        {
            get
            {
                return _extCommand ?? (_extCommand = new DelegateCommand(o =>
                {
                    if (AppCache.ModifiedBeforeSaving &&
                        MessageBox.Show("你有未保存的更改，是否保存？", "退出", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        SavingHelper.SaveFile(AppCache);
                    }

                    Application.Current.Shutdown();
                }));
            }
        }

        public ICommand OpenSettingWindowCommand
        {
            get
            {
                return _openSettingWindowCommand ?? (_openSettingWindowCommand = new DelegateCommand(o =>
                {
                    SettingWindow settingWindow = new SettingWindow(AppCache);
                    settingWindow.ShowDialog();
                },
                    o => false));
            }
        }

        #endregion

        public MainWindowViewModel()
        {
            AppCache = new AppCache();
        }

        public void Init()
        {
            VehicleCountings = new ObservableCollection<DisplayingVehicleCounting>()
            {
                new DisplayingVehicleCounting() { VehicleType = "车型1", Count = 0, CreateTime = new List<TimeSpan>()} ,
                new DisplayingVehicleCounting() { VehicleType = "车型2", Count = 0, CreateTime = new List<TimeSpan>()} ,
                new DisplayingVehicleCounting() { VehicleType = "车型3", Count = 0, CreateTime = new List<TimeSpan>()} ,
                new DisplayingVehicleCounting() { VehicleType = "车型4", Count = 0, CreateTime = new List<TimeSpan>()} ,
            };

            AppCache.VehicleCountings = VehicleCountings.Select(v => v.ToVehicleCounting()).ToList();
        }

        public void SetNoMediaMode(bool value)
        {
            AppCache.NoMediaModeOn = value;

            if (!CanWorking)
            {
                CanWorking = true;
                AppCache.ProjectFileOpened = true;
            }
            else
            {
                CanWorking = false;
                AppCache.ProjectFileOpened = false;
            }

            RaiseAllCommandCanExecuteChanged();
        }

        private void RaiseAllCommandCanExecuteChanged()
        {
            ((DelegateCommand)OpenProjectFileCommand).RaiseCanExecuteChanged();
            ((DelegateCommand)SaveProjectFileCommand).RaiseCanExecuteChanged();
            ((DelegateCommand)SaveAsProjectFileCommand).RaiseCanExecuteChanged();
            ((DelegateCommand)ImportFileCommand).RaiseCanExecuteChanged();
            ((DelegateCommand)ExportFileCommand).RaiseCanExecuteChanged();
            ((DelegateCommand)ExitCommand).RaiseCanExecuteChanged();
        }
    }
}